const box = document.querySelector(".box");
// 下面开始逻辑
const id = window.localStorage.getItem("id");
const token = window.localStorage.getItem("token");
if (!id || !token) {
    window.location.href = `./login.html`;
}

// 判断登录状态是否到期
getLogin();
function getLogin() {
    ajax({
        url: "http://localhost:8888/users/info",
        data: `id=${id}`,
        token: token,
        dataType: "json",
        success(res) {
            if (res.code === 1) {
                $(".loginBox>li:first").text(`欢迎您,${res.info.nickname}`);
                $(".nickName").text(`${res.info.nickname}`);
                $(".shadowNick").text(`${res.info.nickname}`);
            } else {
                window.location.href = `./login.html`;
            }
        },
    });
}

// 这是点击退出登录
outLogin();
function outLogin() {
    $(".outLogin").click(() => {
        window.localStorage.removeItem("id");
        window.localStorage.removeItem("token");
        window.location.reload();
    });
}

//渲染页面
Handler();
function Handler() {
    ajax({
        url: "http://localhost:8888/cart/list",
        data: `id=${id}`,
        dataType: "json",
        token,
        success: function (res) {
            shopCar(res);
        },
        error: function (err, message) {
            console.log("本次请求失败了");
            throw new Error(err);
        },
    });

    function shopCar(res) {
        // . 提前计算出一些内容
        // . 计算有多少个选中的
        // 从 cart 里面筛选出来所有 is_select 为 true 的
        const selectArr = res.cart.filter(item => item.is_select === true);
        const selectNum = selectArr.length;
        // . 计算购买数量和总价
        // 从 cart 里面少选出来所有 is_select 为 true 的
        let totalPrice = 0;
        let totalNum = 0;
        selectArr.forEach((item) => {
            totalPrice += item.current_price * item.cart_number;
            totalNum += item.cart_number;
        });
        let str = "<div class='tBox'>";
        str += `
        <div class="topBox">
            <input class="selectAll" type="checkbox" ${selectNum == res.cart.length ? "checked" : ""}>全选
        </div>`;
        for (let i = 0; i < res.cart.length; i++) {
            str += `<div class="listBox">
        <div class="checkbox">
            <input class="select" data-id="${res.cart[i].goods_id}" type="checkbox" ${res.cart[i].is_select ? "checked" : ""}>
        </div>
        <div class="img">
            <img src="${res.cart[i].img_small_logo}" alt="">
        </div>
        <div class="title">
            <span>${res.cart[i].title}</span>
        </div>
        <div class="price">
            <span>${res.cart[i].current_price}</span>
        </div>
        <div class="number">
            <button class="less" data-id='${res.cart[i].goods_id}'>-</button>
            <input class="count" type="text" value="${res.cart[i].cart_number}">
            <button class="add" data-id='${res.cart[i].goods_id}'>+</button>
        </div>
        <div class="allPrice">
            <span>${(res.cart[i].cart_number * res.cart[i].current_price).toFixed(2)}</span>
        </div>
        <div class="del">
            <button class="delBtn"  data-id='${res.cart[i].goods_id
                }'>删除</button>
        </div>
    </div>`;
        }
        str += `
    </div>
    <div class="bottom">
        <p class="number">
        购买数量 : <span>${totalNum}</span>
        </p>
        <p class="btns">
        <button class="clearAll" ${res.cart.length ? "" : "disabled"
            }>清空购物车</button>
        <button class="clear" ${selectNum ? "" : "disabled"
            }>删除所有已选中</button>
        </p>
        <button class="settlement"  ${selectNum ? "" : "disabled"
            }>去结算</button>
        <p class="totalPrice">
        总价 : <span>${totalPrice.toFixed(2)}</span>
        </p>
    </div>
    `
        box.innerHTML = str;
    }
}
// 点击事件,各种事件委托
box.addEventListener("click", async e => {
    e = e || window.event;
    const target = e.target || srcElement;
    // 这是全选按钮
    if (target.className === "selectAll") {
        const type = target.checked ? 1 : 0;
        const res = await pAjax({
            url: "http://localhost:8888/cart/select/all",
            data: `id=${id}&type=${type}`,
            token,
            dataType: "json",
            method: "post",
        });
        Handler();
    }
    // 这是单选按钮
    if (target.className === "select") {
        const goodsId = target.dataset.id;
        const res = await pAjax({
            url: "http://localhost:8888/cart/select",
            data: `id=${id}&goodsId=${goodsId}`,
            token,
            dataType: "json",
            method: "post",
        });
        Handler();
    }

    //这里是加数量按钮
    if (target.className === "add") {
        const goodsId = target.dataset.id;
        const num = target.previousElementSibling.value - 0 + 1;
        const res = await pAjax({
            url: "http://localhost:8888/cart/number",
            data: `id=${id}&goodsId=${goodsId}&number=${num}`,
            token,
            dataType: "json",
            method: "post",
        });
        Handler();
    }
    //这里是减数量按钮
    if (target.className === "less") {
        const goodsId = target.dataset.id;

        const num = target.nextElementSibling.value - 1;
        if (num <= 0) return;
        const res = await pAjax({
            url: "http://localhost:8888/cart/number",
            data: `id=${id}&goodsId=${goodsId}&number=${num}`,
            token,
            dataType: "json",
            method: "post",
        });
        Handler();
    }
    //这里判断的是清空购物车按钮
    if (target.className === "clearAll") {
        const id = window.localStorage.getItem("id");
        const res = await pAjax({
            url: "http://localhost:8888/cart/clear",
            data: `id=${id}`,
            token,
            dataType: "json",
            method: "get",
        });
        Handler();
    }
    // 这里是判断的是删除按钮
    if (target.className === "delBtn") {
        const id = window.localStorage.getItem("id");
        const goodsId = target.dataset.id;

        const res = await pAjax({
            url: "http://localhost:8888/cart/remove",
            data: `id=${id}&goodsId=${goodsId}`,
            token,
            dataType: "json",
            method: "get",
        });
        Handler();
    }
    //这里是判断删除所有已选中
    if (target.className === "clear") {
        const id = window.localStorage.getItem("id");

        const res = await pAjax({
            url: "http://localhost:8888/cart/remove/select",
            data: `id=${id}`,
            token,
            dataType: "json",
            method: "get",
        });
        Handler();
    }
});

// 样式
getCss();
function getCss() {
    // 登录模块
    $(".ind").mouseenter(function () {
        $(".ind").css("background-color", "white");
        $(".loginShadow").css("display", "block");
    });

    $(".loginShadow").mouseleave(function () {
        $(".ind").css("background-color", "rgba(0,0,0,0)");
        $(".loginShadow").css("display", "none");
    });

    // 首页分类模块
    $(".lef").mouseenter(function () {
        $(".listDis").css("display", "block");
    });
    $(".lef").mouseleave(function () {
        $(".listDis").css("display", "none");
    });

    // 点击商品进入详情页
    // $(".render").on("click", ".goods", (e) => {
    //     e = e || window.event;
    //     const target = e.target;
    //     console.log(target);
    //     window.localStorage.setItem("goods_id", `${target.dataset.id}`);
    //     window.location.href = "./detail.html";
    // });
}


const search = document.querySelector('.top>input')
const searchBox = document.querySelector('.top>ul')

search.oninput = function () {
    const text = this.value
    const script = document.createElement('script')

    script.src = 'https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web&sugsid=34099,33970,34004,33855,33607,26350,22159&wd=' + text + '&req=2&csor=5&pwd=aiqiyi&cb=fn&_=1623047595324'
    document.body.appendChild(script)
    script.remove()
}

function fn(res) {

    if (!res.g) {

        searchBox.style.display = 'none'
        return
    }


    let str = ''
    res.g.forEach(item => {
        str += `<li>${item.q}</li>`
    })
    searchBox.innerHTML = str

    searchBox.style.display = 'block'
}